package com.carlinfo.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class IOUtil
{
	
	public String readFile(File souFile)
	{
		BufferedReader br = null;
		try
		{
			FileInputStream in = new FileInputStream(souFile);
			String readFile = this.readFile(in);
			return readFile;
		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
		} 
		return "";
	}
	public String readFile(InputStream in)
	{
		StringBuffer sb = new StringBuffer();
		try
		{
			InputStreamReader isr = new InputStreamReader(in,"UTF8");
			BufferedReader br = new BufferedReader(isr);
			String line = "";
			while((line = br.readLine())!=null)
			{
//				System.out.println("--->"+line);
				sb = sb.append(line);
			}
		} catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		return sb.toString();
	}
	
	/**
	 * 文件的拷贝
	 * @param is 输入流
	 * @param os 输出流
	 */
	public void copy(InputStream is,OutputStream os) 
	{
		try
		{
			/* 准备管子 */
			BufferedInputStream bis = new BufferedInputStream(is);
			BufferedOutputStream bos = new BufferedOutputStream(os);
			/* 准备桶 */
			byte[] b= new byte[1024 * 1024];
			/* 桶里面用了多少 */
			int len = 0;
			while((len = bis.read(b) ) != -1) 
			{
				bos.write(b,0,len);
			}
		} catch (IOException e)
		{
			e.printStackTrace();
		}finally
		{
			try
			{
				if(is != null)
				{
					is.close(); 
					is = null ; 
				}
				
				if(os != null)
				{
					os.close(); 
					os = null ; 
				}
			} catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args)
	{
		IOUtil ioUtil = new IOUtil();
		File souFile = new File("D:\\project_one\\userscenter\\src_config\\config.json");
		String fileStr = ioUtil.readFile(souFile);
		System.out.println("==基于路径==>" + fileStr);
		
		
		
		/**
		 * 在新版本中可以直接使用，但是老版本的时候必须要写：getClassLoader().getClass();
		 */
//		InputStream is  = IOUtil.class.getResourceAsStream("/config.json");
		InputStream is = IOUtil.class.getClassLoader().getClass().getResourceAsStream("/config.json");
		String readFile = ioUtil.readFile(is);
		JSONObject js = (JSONObject) JSON.parse(readFile);
//		System.out.println(js.get("info"));
//		System.out.println("==classpath==>" + readFile);
	}
}
